﻿
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MX.Core.RabbitMQClient
{
    public class ConsumerWrapper
    {

        public IModel Model { get; set; }

        public DefaultBasicConsumer Consumer { get; set; }

        public IModelWrapper ModelWrapper { get; set; }



        private static ReaderWriterLockSlim GetConsumerlockObj = new ReaderWriterLockSlim();



        static Dictionary<IModelWrapper, ConsumerWrapper> consumerPool = new Dictionary<IModelWrapper, ConsumerWrapper>();

        static public ConsumerWrapper GetConsumerWrapper(string url, string queueName)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException("参数url不能为空，请检查参数");
            if (string.IsNullOrEmpty(queueName))
                throw new ArgumentNullException("参数queueName不能为空，请检查参数");
            GetConsumerlockObj.EnterUpgradeableReadLock();
            try
            {              
                IModelWrapper iModel = ConnectionPool.GetOrCreateChannel(url, queueName, queueName, "exchangeDealer");
                if (consumerPool.ContainsKey(iModel))
                {
                    return consumerPool[iModel];
                }
                try
                {
                    //在队列上定义一个消费者
                    DefaultBasicConsumer consumer = new DefaultBasicConsumer(iModel.Model);
                    //消费队列，并设置应答模式为程序主动应答
                    iModel.Model.BasicConsume(queueName, false, consumer);
                    //阻塞函数，获取队列中的消息
                    consumerPool[iModel] = new ConsumerWrapper()
                    {
                        Consumer = consumer,
                        Model = iModel.Model,
                        ModelWrapper = iModel
                    };
                    return consumerPool[iModel];
                }
                finally
                {
                    iModel.SetNotBusy();
                }
            }
            finally
            {
                GetConsumerlockObj.ExitUpgradeableReadLock();
            }

        }
    }
}
